package stru1.day4;

import java.util.Arrays;

/**
 * 566. 重塑矩阵
 */
public class Solution1 {
    public static void main(String[] args) {
        int[][] mat = new int[][]{{1, 2}, {3, 4}};
        System.out.println(Arrays.deepToString(matrixReshape(mat, 1, 4)));
        System.out.println(Arrays.deepToString(matrixReshape(mat, 2, 4)));
    }

    /**
     * 与matrixReshape1的不同点是：利用整除和取余的单层for代替双层for (两者时间复杂度是相同的)
     */
    public static int[][] matrixReshape(int[][] mat, int r, int c) {
        int m = mat.length, n = mat[0].length;
        if (m * n != r * c) return mat;

        int[][] res = new int[r][c];
        for (int x = 0; x < m * n; ++x) {
            res[x / c][x % c] = mat[x / n][x % n];
        }

        return res;
    }

    /**
     * 对题目理解不到位： 返回原矩阵的条件……
     */
    public static int[][] matrixReshape1(int[][] mat, int r, int c) {
        int m = mat.length, n = mat[0].length;
        if ((r >= m && c >= n) || (r * c < m * n)) return mat;
        int[][] res = new int[r][c];

        int _r = 0, _c = 0;
        for (int[] ints : mat) {
            for (int j = 0; j < n; j++) {
                if (_c == c) {
                    _c = 0;
                    _r++;
                }
                res[_r][_c++] = ints[j];
            }
        }

        return res;
    }
}
